package com.jiegui.payinterface.handler.impl.wxpay.utils;

import org.jdom.input.SAXBuilder;

import java.io.*;
import java.util.*;

/**
 * XML的工具方法
 *
 * @author wuqicheng
 * @date 2021/3/10
 */
public class XmlUtils {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static SortedMap<String, String> getMapFromXml(String strxml) throws Exception {
        if (null == strxml || "".equals(strxml)) {
            return null;
        }

        SortedMap<String, String> m = new TreeMap();
        InputStream in = String2Inputstream(strxml);
        SAXBuilder builder = new SAXBuilder();
        org.jdom.Document doc = builder.build(in);
        org.jdom.Element root = doc.getRootElement();
        List list = root.getChildren();
        for (Object o : list) {
            org.jdom.Element e = (org.jdom.Element) o;
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }
            m.put(k, v);
        }

        // 关闭流
        in.close();
        return m;
    }

    @SuppressWarnings("rawtypes")
    public static SortedMap<Object, Object> getSortedMapFromXml(String strxml) throws Exception {
        if (null == strxml || "".equals(strxml)) {
            return null;
        }

        SortedMap<Object, Object> m = new TreeMap<Object, Object>();
        InputStream in = String2Inputstream(strxml);
        SAXBuilder builder = new SAXBuilder();
        org.jdom.Document doc = builder.build(in);
        org.jdom.Element root = doc.getRootElement();
        List list = root.getChildren();
        for (Object o : list) {
            org.jdom.Element e = (org.jdom.Element) o;
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }

            m.put(k, v);
        }

        // 关闭流
        in.close();

        return m;
    }

    /**
     * 获取子结点的xml
     * @return String
     */
    @SuppressWarnings("rawtypes")
    public static String getChildrenText(List children) {
        StringBuilder sb = new StringBuilder();
        if (!children.isEmpty()) {
            for (Object child : children) {
                org.jdom.Element e = (org.jdom.Element) child;
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<").append(name).append(">");
                if (!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</").append(name).append(">");
            }
        }

        return sb.toString();
    }

    /**
     * map转xml格式(多结构拼接生成)
     * @param sortedMap map
     */
    public static String mapToSignXml(SortedMap<Object, Object> sortedMap) {
        StringBuilder builder = new StringBuilder();
        for (Object o : sortedMap.keySet()) {
            Object value = sortedMap.get(o);
            builder.append("<").append(o).append(">");
            if (value instanceof SortedMap) {
                SortedMap<Object, Object> sortedMap1 = (SortedMap<Object, Object>) value;
                builder.append(mapToSignXml(sortedMap1));
            } else {
                builder.append(value);
            }
            builder.append("</").append(o).append(">");

        }
        return builder.toString();
    }


    public static InputStream String2Inputstream(String str) {
        return new ByteArrayInputStream(str.getBytes());
    }

    /**
     * 参数转换为XML
     */
    @SuppressWarnings("rawtypes")
    public static String parseXML(SortedMap parameters) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        for (Object e : es) {
            Map.Entry entry = (Map.Entry) e;
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (null != v && !"".equals(v) && !"appkey".equals(k)) {

                sb.append("<").append(k).append(">").append(parameters.get(k)).append("</").append(k).append(">\n");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }

    /**
     * 获取随机标示
     */
    public static String getNonceStr() {
        Random random = new Random();
        return MD5.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
    }

    /**
     * 生成签名
     */
    @SuppressWarnings("rawtypes")
    public static String createSign(SortedMap<String, String> parameters, String key) {
        StringBuilder sb = new StringBuilder();
        Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序（升序）
        for (Object e : es) {
            Map.Entry entry = (Map.Entry) e;
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k).append("=").append(v).append("&");
            }
        }
        sb.append("key=").append(key);
        return Objects.requireNonNull(MD5.MD5Encode(sb.toString(), "UTF-8")).toUpperCase();
    }

}
